package com.kaka.jsonmap.core;

import com.alibaba.fastjson2.JSON;
import com.kaka.jsonmap.model.MappingConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Parses mapping configuration from JSON files
 */
public class ConfigurationParser {
    private static final Logger logger = LoggerFactory.getLogger(ConfigurationParser.class);




    /**
     * Loads a mapping configuration from an input stream
     *
     * @param inputStream The input stream containing the configuration
     * @return The parsed mapping configuration
     * @throws IOException if loading fails
     */
    public static MappingConfig loadConfiguration(InputStream inputStream) throws IOException {
        try {
            // 去除//注释
            String configJsonWithComments = readInputStreamToString(inputStream);
            String cleanConfigJson = JsonPreprocessor.removeComments(configJsonWithComments);
            return JSON.parseObject(cleanConfigJson, MappingConfig.class);
        } catch (IOException e) {
            logger.error("Failed to load configuration from input stream", e);
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String readInputStreamToString(InputStream inputStream) throws Exception {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString().trim();
    }


} 